import React, { useState, useEffect, useCallback } from 'react';
import { Plus, CheckCircle, XCircle, RefreshCw, Trash2, Star, Key, Clock } from 'lucide-react';
import { accountApi } from '../api';
import type { HeyGenAccount } from '../api/types';
import { useApiError } from '../hooks/useApiError';
import { useConfirm } from '../hooks/useConfirm';
import { toast } from '../stores/toastStore';

const Accounts: React.FC = () => {
  const { handleError } = useApiError();
  const { confirmDelete, setLoading: setConfirmLoading, ConfirmComponent } = useConfirm();
  const [accounts, setAccounts] = useState<HeyGenAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddForm, setShowAddForm] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState<number | null>(null);

  // 添加账户表单状态
  const [newAccount, setNewAccount] = useState({
    name: '',
    api_key: '',
  });

  const loadAccounts = useCallback(async () => {
    try {
      setLoading(true);
      const data = await accountApi.list();
      const accountsList = data?.rows || [];
      setAccounts(accountsList);
    } catch (error) {
      handleError(error, '加载AI服务账户列表失败');
    } finally {
      setLoading(false);
    }
  }, [handleError]);

  useEffect(() => {
    loadAccounts();
  }, [loadAccounts]);

  const handleAddAccount = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await accountApi.create(newAccount);
      setNewAccount({ name: '', api_key: '' });
      setShowAddForm(false);
      toast.success('AI服务账户添加成功');
      loadAccounts();
    } catch (error) {
      handleError(error, '添加AI服务账户失败');
    }
  };

  const handleActivateAccount = async (id: number) => {
    try {
      await accountApi.activate(id);
      toast.success('AI服务账户已激活');
      loadAccounts();
    } catch (error) {
      handleError(error, '激活AI服务账户失败');
    }
  };

  const handleRefreshQuota = async (id: number) => {
    try {
      setIsRefreshing(id);
      await accountApi.refreshQuota(id);
      toast.success('配额刷新成功');
      loadAccounts();
    } catch (error) {
      handleError(error, '刷新配额失败');
    } finally {
      setIsRefreshing(null);
    }
  };

  const handleDeleteAccount = async (id: number, name: string) => {
    const confirmed = await confirmDelete(`确定要删除AI服务账户吗？`, `${name}`);

    if (!confirmed) return;

    try {
      setConfirmLoading(true);
      await accountApi.delete(id);
      toast.success('AI服务账户删除成功');
      loadAccounts();
    } catch (error) {
      handleError(error, '删除AI服务账户失败');
    } finally {
      setConfirmLoading(false);
    }
  };

  const formatQuota = (remainingQuota: number | undefined) => {
    if (!remainingQuota) return '0';
    return remainingQuota.toString();
  };

  const formatDate = (date: string | undefined) => {
    if (!date) return '未知';
    return new Date(date).toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <RefreshCw className="w-8 h-8 animate-spin text-cyan-500" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-100">AI服务商配置</h1>
          <p className="text-gray-400 mt-1">配置AI视频生成服务的账户和API密钥</p>
        </div>
        <button
          onClick={() => setShowAddForm(true)}
          className="flex items-center space-x-2 px-4 py-2 bg-gradient-to-r from-cyan-500 to-blue-500 hover:from-cyan-600 hover:to-blue-600 text-white rounded-lg transition-all transform hover:scale-105 cursor-pointer"
        >
          <Plus className="w-4 h-4" />
          <span>添加AI账户</span>
        </button>
      </div>

      {/* 添加账户弹窗 */}
      {showAddForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-gray-900 border border-gray-700 rounded-xl p-6 w-full max-w-md">
            <h2 className="text-xl font-bold text-gray-100 mb-4">添加新AI账户</h2>
            <form onSubmit={handleAddAccount} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">AI服务商名称</label>
                <input
                  type="text"
                  value={newAccount.name}
                  onChange={e => setNewAccount({ ...newAccount, name: e.target.value })}
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-600 rounded-lg text-gray-100 focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
                  placeholder="为AI服务商设置一个名称"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">API 密钥</label>
                <input
                  type="password"
                  value={newAccount.api_key}
                  onChange={e => setNewAccount({ ...newAccount, api_key: e.target.value })}
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-600 rounded-lg text-gray-100 focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
                  placeholder="输入 API 密钥"
                  required
                />
              </div>
              <div className="flex space-x-3 pt-4">
                <button
                  type="submit"
                  className="flex-1 bg-gradient-to-r from-cyan-500 to-blue-500 hover:from-cyan-600 hover:to-blue-600 text-white py-2 rounded-lg transition-all cursor-pointer"
                >
                  确认添加
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setShowAddForm(false);
                    setNewAccount({ name: '', api_key: '' });
                  }}
                  className="flex-1 bg-gray-700 hover:bg-gray-600 text-white py-2 rounded-lg transition-colors cursor-pointer"
                >
                  取消
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 账户列表 */}
      <div className="space-y-4">
        {accounts.length === 0 ? (
          <div className="bg-gray-900 border border-gray-800 rounded-xl p-12 text-center">
            <Key className="w-16 h-16 text-gray-600 mx-auto mb-4" />
            <h3 className="text-xl font-medium text-gray-300 mb-2">暂无AI服务账户</h3>
            <p className="text-gray-500 mb-6">添加您的第一个AI服务账户以开始使用</p>
            <button
              onClick={() => setShowAddForm(true)}
              className="px-6 py-2 bg-gradient-to-r from-cyan-500 to-blue-500 hover:from-cyan-600 hover:to-blue-600 text-white rounded-lg transition-all cursor-pointer"
            >
              添加首个AI账户
            </button>
          </div>
        ) : (
          accounts.map(account => (
            <div
              key={account.id}
              className={`bg-gray-900 border rounded-xl p-6 transition-all ${
                account.is_active
                  ? 'border-cyan-500 shadow-lg shadow-cyan-500/20'
                  : 'border-gray-800 hover:border-gray-700'
              }`}
            >
              <div className="flex items-start justify-between">
                {/* 账户信息 */}
                <div className="flex-1">
                  <div className="flex items-center space-x-3 mb-4">
                    <h3 className="text-xl font-semibold text-gray-100">{account.name}</h3>
                    {account.is_active && (
                      <span className="flex items-center space-x-1 px-3 py-1 bg-gradient-to-r from-cyan-500/20 to-blue-500/20 text-cyan-400 text-xs font-medium rounded-full">
                        <Star className="w-3 h-3 fill-current" />
                        <span>当前使用</span>
                      </span>
                    )}
                    <span
                      className={`flex items-center space-x-1 px-3 py-1 text-xs font-medium rounded-full ${
                        account.is_active
                          ? 'bg-green-500/20 text-green-400'
                          : 'bg-gray-500/20 text-gray-400'
                      }`}
                    >
                      {account.is_active ? (
                        <>
                          <CheckCircle className="w-3 h-3" />
                          <span>活跃</span>
                        </>
                      ) : (
                        <>
                          <XCircle className="w-3 h-3" />
                          <span>非活跃</span>
                        </>
                      )}
                    </span>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    {/* 账户详情 */}
                    <div className="space-y-2">
                      {account.email && (
                        <div className="flex items-start">
                          <span className="text-gray-500 text-sm w-16">邮箱</span>
                          <span className="text-gray-300 text-sm">{account.email}</span>
                        </div>
                      )}
                      {account.username && (
                        <div className="flex items-start">
                          <span className="text-gray-500 text-sm w-16">用户名</span>
                          <span className="text-gray-300 text-sm">{account.username}</span>
                        </div>
                      )}
                    </div>

                    {/* 配额信息 */}
                    <div className="space-y-2">
                      <div className="flex items-start">
                        <span className="text-gray-500 text-sm w-16">配额</span>
                        <span className="text-gray-300 text-sm font-medium">
                          {formatQuota(account.remaining_quota)} 秒
                        </span>
                      </div>
                      {account.last_sync_at && (
                        <div className="flex items-start">
                          <span className="text-gray-500 text-sm w-16">同步</span>
                          <span className="text-gray-400 text-xs flex items-center">
                            <Clock className="w-3 h-3 mr-1" />
                            {formatDate(account.last_sync_at)}
                          </span>
                        </div>
                      )}
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex items-center justify-end space-x-2">
                      {!account.is_active && (
                        <button
                          onClick={() => handleActivateAccount(account.id)}
                          className="px-3 py-1.5 bg-cyan-600 hover:bg-cyan-700 text-white text-sm rounded-lg transition-colors cursor-pointer"
                        >
                          设为活跃
                        </button>
                      )}
                      <button
                        onClick={() => handleRefreshQuota(account.id)}
                        disabled={isRefreshing === account.id}
                        className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-white text-sm rounded-lg transition-colors disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed"
                      >
                        <RefreshCw
                          className={`w-4 h-4 ${isRefreshing === account.id ? 'animate-spin' : ''}`}
                        />
                      </button>
                      <button
                        onClick={() => handleDeleteAccount(account.id, account.name)}
                        className="px-3 py-1.5 bg-gray-700 hover:bg-red-600 text-white text-sm rounded-lg transition-colors cursor-pointer"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Unified Confirm Dialog */}
      <ConfirmComponent />
    </div>
  );
};

export default Accounts;
